package com.proj.util;

import com.proj.bean.User;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;

public class SYS {
    //文件上传保存路径
    public static final String FILE_UPLOAD_DIR="D:\\Program program\\easyupload\\";
    //上传文件 访问 前缀路径
    public static final String FILE_UPLOAD_URL="easyfile";

    //用户登录常量
    public static final String SHOPPING_LOGIN_USER="SHOPPING_LOGIN_USER";
    //管理员登陆session的attribute常量
    public static final String SYSTEM_LOGIN_ADMIN="SYSTEM_LOGIN_ADMIN";

    public static int getLoginUserID(HttpSession session){
        User user=(User)session.getAttribute(SHOPPING_LOGIN_USER);
        return user.getId();
    }

    //注册加密
    public static String digest(String pass) {
//        String pass="123123";

//        //简单加密  MD5加密
//        String digestPass= DigestUtils.md5DigestAsHex(pass.getBytes());
//        System.out.println("简单加密:"+digestPass);
        //多次加密。
//        //盐值加密
//        String salt_="abc";
//        String pass_=DigestUtils.md5DigestAsHex((pass+salt_).getBytes());
//        System.out.println("盐值加密:"+pass_);
        //随即次数随机盐值加密
        int countIndex=(int) (Math.random()*HEX_CHAR_ARR.length);
        int saltIndex=(int) (Math.random()*HEX_CHAR_ARR.length);
        int count=HEX_CHAR_ARR[countIndex];
        char salt= (char) HEX_CHAR_ARR[saltIndex];

        pass=pass+salt;
            //加盐
        for(int i=0;i<count;i++){
            pass=DigestUtils.md5DigestAsHex(pass.getBytes());
        }
//        System.out.println("salt:"+salt);
//        System.out.println("count:"+count);
//        System.out.println("pass:"+pass);

//        String c= String.valueOf(count);
//        String password=salt+c+pass;

        char countChar=(char) count;
        String password=salt+pass+countChar;

//        System.out.println("Pass:"+password);

        return password;

    }

    public static final int [] HEX_CHAR_ARR={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        //'0':48        'a':97

    //登陆验证
    public static boolean checkPass(String pass,String hexPass){
        char salt=hexPass.charAt(0);                        //盐值
        char count=hexPass.charAt(hexPass.length()-1);      //次数
        pass=pass+salt;
        for(int i=0;i<count;i++){
            pass=DigestUtils.md5DigestAsHex(pass.getBytes());
        }
        String text=salt+pass+count;

        return text.equals(hexPass);
    }

}
